import { newlogin, changeUser } from '@/api/login'
import { MessageBox } from 'element-ui'

const userLoginFun = (param) => {
  return new Promise((resolve, reject) => {
    newlogin(param).then(response => {
      if (response.again) {
        MessageBox.confirm(
          '登录失败,该用户已经在其他设备登录了。是否登录到此设备',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          // 顶号
          killTokenFun(param).then(res => {
            resolve(res)
          })
        }).catch(() => {

        })
      } else {
        const data = response.result
        resolve(data)
      }
    }).catch(error => {
      console.log(error)
      resolve(false)
    })
  })
}

// 登录顶号 注销 token
const killTokenFun = (param) => {
  const query = {
    'appId': param.appId,
    'userId': param.userId
  }
  return new Promise((resolve, reject) => {
    changeUser(query).then(res => {
      if (res.code === '0') {
        userLoginFun(param).then(res => {
          resolve(res)
        })
      }
    }).catch(e => {
      reject(e)
    })
  })
}

const editList = (list) => {
  let adminList = []
  list.appAuthorities.forEach(item => {
    // item.roleAuthorities.forEach(item2 => {
    // const List = item2.resources
    const List = item.roleAuthorities
    adminList = adminList.concat(List)
    // })
  })
  adminList.forEach(el => {
    el.ruleCode = el.roleCode
  })
  return adminList
}

export {
  userLoginFun, // 登录
  killTokenFun, // 踢人顶号
  editList// 登陆后编辑权限ruleList
}
